//
//  MyWebView.m
//  myGame
//
//  Created by 李钰 on 2017/12/14.
//  Copyright © 2017年 ImDemo. All rights reserved.
//

#import "MyWebView.h"
#import <WebKit/WebKit.h>
#import "ShareProcessPool.h"
#define IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
@interface MyWebView()<WKNavigationDelegate,WKUIDelegate>
@property (nonatomic, strong)WKWebView * webKitView;
@property (nonatomic, strong)UIProgressView *progressView;
@property (nonatomic, strong)UIActivityIndicatorView * active;
@property (nonatomic, strong)UIView    * bottomView;
@end
@implementation MyWebView
{
    NSString * _url;
}
- (id)initWithUrl:(NSString *)url
{
    if ([super initWithFrame: CGRectMake(0, 0, ScreenWidth, ScreenHeight)])
    {
        _url = url;
        [self deleteWebCache];
        self.backgroundColor = RGB(243, 243, 247);
        [self addSubview: self.webKitView];
        if (url) {
            [self.webKitView loadRequest:[NSURLRequest requestWithURL: [NSURL URLWithString: url]]];
        }
        [self addSubview: self.bottomView];
    }
    return self;
}
- (WKWebView *)webKitView {
    if (_webKitView == nil) {
        ///WK WebView配置
        WKUserContentController* userContentController = [WKUserContentController new];
        WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: @"document.cookie = 'skey=skeyValue';" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly: NO];
        [userContentController addUserScript: cookieScript];
        
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = userContentController;
        configuration.processPool = [ShareProcessPool Instance];
        
        if (IOS_VERSION >= 10.0) {
            if (@available(iOS 10.0, *)) {
                configuration.dataDetectorTypes = WKDataDetectorTypeLink;
            } else {
                // Fallback on earlier versions
            }
        }
        ///WK WebView
        _webKitView= [[WKWebView alloc] initWithFrame: CGRectMake(0, 0, ScreenWidth, ScreenHeight-self.bottomView.height) configuration:configuration];
        _webKitView.navigationDelegate = self;
        _webKitView.backgroundColor = self.backgroundColor;
        _webKitView.allowsBackForwardNavigationGestures = NO;
        _webKitView.UIDelegate = self;
        _webKitView.scrollView.bounces = YES;
    }
    return _webKitView;
}
- (UIView *)bottomView
{
    if (nil == _bottomView) {
        CGFloat height = 44+UI_TAB_BOTTOM_SAFE_PADDING;
        _bottomView = [[UIView alloc] initWithFrame: CGRectMake(0, ScreenHeight-height, ScreenWidth, height)];
        _bottomView.backgroundColor = [UIColor whiteColor];
        NSArray * arr = @[@"首页",@"后退",@"前进",@"刷新"];
        NSArray * arrIcon = @[@"webhome",@"webback",@"webgo",@"webrefresh"];
        CGFloat btnwidth = ScreenWidth/4;
        for (NSInteger i = 0; i<arr.count; i++) {
            UIButton * btn = [UIButton buttonWithType: UIButtonTypeCustom];
            NSString * title = arr[i];
            [btn setTitle: title forState: UIControlStateNormal];
            [btn setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
            [btn setImage: [UIImage imageNamed: arrIcon[i]] forState: UIControlStateNormal];
            btn.tag=i;
            [btn addTarget: self action: @selector(onBtn:) forControlEvents: UIControlEventTouchUpInside];
            [_bottomView addSubview: btn];
            btn.titleLabel.font = [UIFont systemFontOfSize: 10];
            btn.frame = CGRectMake(i*btnwidth, 0, btnwidth, 44);
            CGFloat space = 20;
            [btn setImageEdgeInsets: UIEdgeInsetsMake(-space, space+4, 0, 0)];
            [btn setTitleEdgeInsets: UIEdgeInsetsMake(space, -space, 0, 0)];
        }
    }
    return _bottomView;
}
- (UIActivityIndicatorView *)active {
    if (!_active) {
        UIActivityIndicatorView *active = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _active = active;
        _active.frame = CGRectMake((ScreenWidth - 80.0)/ 2.0, (ScreenHeight - 80.0)/ 2.0, 80.0, 80.0);
        [self.webKitView addSubview:_active];
        [_active startAnimating];
    }
    return _active;
}
- (void)deleteWebCache
{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSSet *websiteDataTypes = [NSSet setWithArray:@[
                                                        WKWebsiteDataTypeDiskCache,
                                                        WKWebsiteDataTypeMemoryCache,
                                                        ]];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        //// Execute
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            // Done
        }];
    } else {
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
    }
}
- (void)onBtn:(UIButton *)sender
{
    switch (sender.tag) {
        case 0://首页
        {
            if (_url) {
                [self.webKitView loadRequest:[NSURLRequest requestWithURL: [NSURL URLWithString: _url]]];
            }
        }
            break;
        case 1://后退
        {
            if ([self.webKitView canGoBack]) {
                [self.webKitView goBack];
            }
        }
            break;
        case 2://前进
        {
            if ([self.webKitView canGoForward]) {
                [self.webKitView goForward];
            }
        }
            break;
        case 3://刷新
        {
            [self.webKitView reload];
        }
            break;
        default:
            break;
    }
}
#pragma mark - WK Navigation Delegate

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if (navigationAction.targetFrame.isMainFrame == NO) {
        [webView evaluateJavaScript:@"var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}" completionHandler:nil];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    [self.active startAnimating];
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    decisionHandler (WKNavigationResponsePolicyAllow);
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    [self.active stopAnimating];
}
// 页面加载失败 || 主页数据加载发生错误 时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [self.active stopAnimating];
}
//提交发生错误时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [self.active stopAnimating];
}
@end


